﻿import bus from '@/components/common/js/bus';
import { Notification, Message } from "element-ui";
import store from '@/store';
import router from '@/router';
import { HashMap } from './utile';
import { dataHide } from '@/utils/filter';
import { saveOrUpdateCsLeave, saveOrUpdateCallLog, updateStartTime, updateEndTime, saveSheetRecContact } from '@/service/busi/softPhone';

import {
    InitWebSocket,
    GetLocalIP,
    SimulateCall,
    SignIn,
    SignOut,
    Busy,
    Rest,
    Idle,
    Answer,
    Hungup,
    Hold,
    UnHold,
    Mute,
    UnMute,
    MakeCall,
    Consult,
    Conference,
    Transfer,
    Consult2Conference,
    Consult2Transfer,
    CancelTransfer,
    CancelConsult,
    CancelConfrence,
    EndConference,
    EndConsult,
    Insert,
    Intercept,
    Wisper,
    Listen,
    EndInsert,
    EndListen,
    EndWisper,
    SwitchMonitor,
    ForceLogOut,
    EnterAcw,
    LeaveAcw,
    ForceSetStatus,
    SendDTMF,
    SetCtiData,
    SetSysPara
} from "./UniSoftPhone.js";

//事件定义
var EventCommands = {
	EVENT_ERROR : 0,
	EVENT_STATECHANGE:1,
	EVENT_BUSYSUCCEED:2,
	EVENT_IDLESUCCEED:3,
	EVENT_WRAPUP	:4,
	EVENT_SIGNOUTSUCCEED : 5,
	EVENT_RINGING : 6,
	EVENT_CONNECTED : 7,
	EVENT_DISCONNECTED : 8,
	EVENT_HOLDSUCCEED : 9,
	EVENT_UNHOLDSUCCEED : 10,
	EVENT_REMOTEALERTING:11,
	EVENT_CONSULTDIALING :12,
	EVENT_CONSULTFAILED :13,
	EVENT_CONSULTSUCCEED : 14,
	EVENT_CONSULTTRANSFDIALING:15,
	EVENT_CONSULTTRANSFSUCCEED : 16,
	EVENT_CONSULTRANSFFAILED : 17,
	EVENT_TRANSFDIALING : 18,
	EVENT_TRANSFSUCCEED : 19,
	EVENT_TRANSFFAILED : 20,
	EVENT_CONFDIALING : 21,
	EVENT_CONFSUCCEED : 22,
	EVENT_CONFFAILED : 23,
	EVENT_CONSULTCONFDIALING : 24,
	EVENT_CONSULTCONFSUCCEED : 25,
	EVENT_CONSULTCONFFAILED : 26,
	EVENT_LISTENSUCCEED : 27,
	EVENT_INSERTSUCCEED : 28,
	EVENT_WISPERSUCCEED : 29,
	EVENT_ENDLISTENSUCCEED : 30,
	EVENT_ENDINSERTSUCCEED : 31,
	EVENT_ENDWISPERSUCCEED : 32,
	EVENT_RECEIVEMESSAGE : 33,
	EVENT_SIGNINSUCCEED:34,
	EVENT_ONAGENTSTATE : 35,
	EVENT_RECORDSUCCESS : 36,
	EVENT_RESTSUCCESS : 37,
	EVENT_ONGETLOCALIP:38
};
var statedisc=new Array();
var menumap = new HashMap();

var CALL_ID = null; // 工单id 关联服务记录用
var BUSI_TYPE = null; // 关联类型 GD:工单 QZD:求助单
var SOURCE_TYPE_ID = null; // 求助来源
var FROM_CODE = null; // 来源id
var CUS_CODE = null; // 客户id
var CUS_NAME = null; // 客户姓名
var CUS_CARD = null; // 客户证件号
var MOBILE = null; // 客户手机号码

function StateInit()
{
	statedisc[0]="签出";
	statedisc[1]="就绪";
	statedisc[2]="忙碌";
	statedisc[3]="话后";
	statedisc[4]="振铃";
	statedisc[5]="呼出振铃";
	statedisc[6]="通话中";
	statedisc[7]="保持";
	statedisc[8]="咨询拨号中";
	statedisc[9]="咨询中";
	statedisc[10]="会议拨号中";
	statedisc[11]="会议中";
	statedisc[12]="转接拨号中";
	statedisc[13]="转接中";
	statedisc[14]="被咨询中";
	statedisc[15]="被会议中";
	statedisc[16]="求助拨号中";
	statedisc[17]="求助中";
	statedisc[18]="监听中";
	statedisc[19]="强插中";
	statedisc[20]="耳语中";
	statedisc[21]="离席中";
    statedisc[22]="外呼拨号中";
    
    var obj = {
        stateName: statedisc[0],
        stateCode: "0"
    }
    return obj;
	
}
function OnWebSocketDisConnect()
{
    //这里添加处理和服务器断开后的操作
    Notification({
        title: '提示',
        type: 'error',
        duration: 1500,
        message: '服务器断开连接！'
    })
    bus.$emit('socketDis');
}
function OnSoftPhoneEvent(eventData){
	if( eventData.cmd == EventCommands.EVENT_STATECHANGE ){
		//事件状态变化接口
		var sAgentID = eventData.parameters.AgentID;
		var sPreState = eventData.parameters.PreState;
		var sState =eventData.parameters.State;
		OnStateChange(sAgentID,sPreState,sState);
	}else if( eventData.cmd == EventCommands.EVENT_ERROR )
	{
		//alert(obj.cmd+";"+obj.cmd_description+";"+obj.parameters.AgentID+";"+obj.parameters.ErrorCode);
		var sAgentID = eventData.parameters.AgentID;
		var sErrorCode = eventData.parameters.ErrorCode;
		var sErrorDisp = eventData.parameters.ErrorDesc;
		OnError(sAgentID,sErrorCode,sErrorDisp);
		//事件错误报告接口
	}else if( eventData.cmd == EventCommands.EVENT_RINGING )
	{
		var sAgentID = eventData.parameters.AgentID;
		var sUCID =  eventData.parameters.UCID;
		var sAni = eventData.parameters.ANI;
		var sDnis = eventData.parameters.DNIS;
		var sCTIData = eventData.parameters.CTIData;
		OnRinging(sAgentID,sUCID,sAni,sDnis,sCTIData);
		//振铃事件
	}else if( eventData.cmd == EventCommands.EVENT_CONNECTED )
	{
		var sAgentID = eventData.parameters.AgentID;
		var sUCID =  eventData.parameters.UCID;
		var sAni = eventData.parameters.ANI;
		var sDnis = eventData.parameters.DNIS;
		var sDirect = eventData.parameters.Direction;
		var sCTIData = eventData.parameters.CTIData;
		var sType = eventData.parameters.Type;
		OnConnected(sAgentID,sUCID,sAni,sDnis,sDirect,sCTIData,sType);
		//通话事件
	}
	else if( eventData.cmd == EventCommands.EVENT_DISCONNECTED )
	{
		var sAgentID = eventData.parameters.AgentID;
		var sUCID =  eventData.parameters.UCID;
		var sReleasePart = eventData.parameters.ReleasePart;
		var sReleaseType = eventData.parameters.ReleaseType;
		OnDisconnected(sAgentID,sUCID,sReleasePart,sReleaseType);
		//挂机事件
	}else if(eventData.cmd == EventCommands.EVENT_SIGNINSUCCEED)
	{
		var sAgentID = eventData.parameters.AgentID;
		var sStation = eventData.parameters.Station;
		var sSkillGroup = eventData.parameters.SkillGroup;
		OnSignInSucceed(sAgentID,sStation,sSkillGroup);
	}
	else if(eventData.cmd == EventCommands.EVENT_SIGNOUTSUCCEED)
	{
		var sAgentID = eventData.parameters.AgentID;
		
		OnSignOutSucceed(sAgentID);
	}else if(eventData.cmd == EventCommands.EVENT_REMOTEALERTING)
	{
		var sAgentID = eventData.parameters.AgentID;
		var sUCID =  eventData.parameters.UCID;
		var sCalled = eventData.parameters.strCalled;
		OnRemoteAlerting(sAgentID,sUCID,sCalled);
	}
	else if(eventData.cmd == EventCommands.EVENT_TRANSFSUCCEED)
	{
		var sAgentID = eventData.parameters.AgentID;
		var sUCID =  eventData.parameters.UCID;
    }
    else if(eventData.cmd == EventCommands.EVENT_RESTSUCCESS)
	{
        var sAgentID = eventData.parameters.AgentID;
        OnRestSucceed(sAgentID);
    }
    else if(eventData.cmd == EventCommands.EVENT_ONGETLOCALIP)
	{
		var localip = eventData.parameters.LocalIP;
		OnGetLocalIP(localip);
    }
    else if(eventData.cmd == EventCommands.EVENT_RECORDSUCCESS)
	{
		var sAgentID = eventData.parameters.AgentID;
		var sUCID = eventData.parameters.UCID;
		var sSelfRecFileName = eventData.parameters.SelfRecFileName;
		OnRecordSuccess(sAgentID,sUCID,sSelfRecFileName);
    }
}

function OnForceLogoutSucceed(sAgentID)
{
    notify('OnForceLogoutSucceed：sAgentID='+sAgentID);
    bus.$emit('monitEvent', { event: 'OnForceLogoutSucceed', sAgentID });
}
function OnForceLogoutFailed(sAgentID,sFailedReason)
{
    notify('OnForceLogoutSucceed：sAgentID='+sAgentID+";sFailedReason="+sFailedReason);
    bus.$emit('monitEvent', { event: 'OnForceLogoutFailed', sAgentID,sFailedReason });
}

function OnForceIdleSucceed(sAgentID)
{
    notify('OnForceIdleSucceed='+sAgentID);
    bus.$emit('monitEvent', { event: 'OnForceIdleSucceed', sAgentID });
}
function OnforceIdleFailed(sAgentID,sFailedReason)
{
    notify('OnforceIdleFailed='+sAgentID+";sFailedReason="+sFailedReason);
    bus.$emit('monitEvent', { event: 'OnforceIdleFailed', sAgentID });
}

function OnForceBusySucceed(sAgentID)
{
    notify('OnForceBusySucceed='+sAgentID);
    bus.$emit('monitEvent', { event: 'OnForceBusySucceed', sAgentID });
}
function OnForceBusyFailed(sAgentID,sFailedReason)
{
    notify('OnForceBusyFailed='+sAgentID+";sFailedReason="+sFailedReason);
    bus.$emit('monitEvent', { event: 'OnForceBusyFailed', sAgentID,sFailedReason });
}
//////////////////////////////////
function OnListenSucceed(sAgentID,sDestAgentID,sUcid)
{
    notify('OnListenSucceed：sAgentID='+sAgentID+";sDestAgentID="+sDestAgentID+";sUcid="+sUcid);
    bus.$emit('monitEvent', { event: 'OnListenSucceed', sAgentID,sDestAgentID,sUcid });
}
function OnInsertSucceed(sAgentID,sDestAgentID,sUcid)
{
    notify('OnInsertSucceed：sAgentID='+sAgentID+";sDestAgentID="+sDestAgentID+";sUcid="+sUcid);
    bus.$emit('monitEvent', { event: 'OnInsertSucceed', sAgentID,sDestAgentID,sUcid });
}
function OnGetAllAgentState(sAgentID,sAgentStateMsg)
{
    notify('OnGetAllAgentState：sAgentID='+sAgentID+";sAgentStateMsg="+sAgentStateMsg);
    bus.$emit('monitEvent', { event: 'OnGetAllAgentState', sAgentID,sAgentStateMsg });
}
function OnListenFailed(sAgentID,sDestAgentID,sFailedReason)
{
    notify('OnListenFailed：sAgentID='+sAgentID+";sDestAgentID="+sDestAgentID+";sFailedReason="+sFailedReason);
    bus.$emit('monitEvent', { event: 'OnListenFailed', sAgentID,sDestAgentID,sFailedReason });
}
function OnInsertFailed(sAgentID,sDestAgentID,sFailedReason)
{
    notify('OnInsertFailed：sAgentID='+sAgentID+";sDestAgentID="+sDestAgentID+";sFailedReason="+sFailedReason);
    bus.$emit('monitEvent', { event: 'OnInsertFailed', sAgentID,sDestAgentID,sFailedReason });
}
function OnInterceptSuccess(sAgentID,sDestAgentID,sUcid)
{
    notify('OnInterceptSuccess：sAgentID='+sAgentID+";sDestAgentID="+sDestAgentID+";sUcid="+sUcid);
    bus.$emit('monitEvent', { event: 'OnInterceptSuccess', sAgentID,sDestAgentID,sUcid });
}
function OnInterceptFailure(sAgentID,sDestAgentID,sFailedReason)
{
    notify('OnInterceptFailure：sAgentID='+sAgentID+";sDestAgentID="+sDestAgentID+";sFailedReason="+sFailedReason);
    bus.$emit('monitEvent', { event: 'OnInterceptFailure', sAgentID,sDestAgentID,sFailedReason });
}

function OnRecordSuccess(agentid,ucid,selfRecFileName)
{
    notify('ucid='+ucid+";selfRecFileName="+selfRecFileName);
    let servId = store.state.phone.servId;
    let url = selfRecFileName;
    let index = url.indexOf(':');
    if(index > -1) {
        url = url.slice(index + 1);
    }
    let params = {
        id: servId,
        callCont: url
    }
    saveOrUpdateCallLog(params).then(res => {
        if(res.data.code == 1000) {
            notify('录音地址更新成功！')
        }
    })
}

function OnGetLocalIP(localip)
{
    notify('LocalIP='+localip);
    bus.$emit("watchState", 'IP', { localip });
}

function OnRestSucceed(sAgentID)
{
    // 申请离席 成成离席记录
    let params = {
        leaveTypeCode: 'LXZ'
    }
    saveOrUpdateCsLeave(params).then(res => {
        if(res.data.code == 1000) {
            let data = res.data.data;
            if(data) {
                store.dispatch('updateRestId', data.id);
            }
            notify('生成离席记录成功！')
        }
    })
	notify('OnTransfSucceed:'+sAgentID);
}
function OnTransfSucceed(sAgentID,sUCID)
{
    notify('OnTransfSucceed:'+sAgentID)
}
function OnSignInSucceed(sAgentID,sStation,sSkillGroup)
{
}
function OnSignOutSucceed(sAgentID)
{
}
function OnRemoteAlerting(sAgent,sUCID,sCalled)
{
}
function OnStateChange(sAgentID,PreState,State)
{
	bus.$emit("watchState", State);
}

function makeCallFun(num, config) { // 外呼电话
    notify('外呼电话333', num, config);
    if(!num) {
        Notification({
            title: '提示',
            type: 'warning',
            duration: 1500,
            message: '外呼号码不能为空'
        })
        return
    }

    let softphoneAuth = store.state.phone.softphoneAuth;
    if(!softphoneAuth) {
        Notification({
            title: '提示',
            type: 'warning',
            duration: 1500,
            message: '您没有软电话外呼权限，请联系管理员！'
        })
        return
    }

    let phoneState = store.state.phone.phoneState;
    if(['1', '2', '3', '21'].indexOf(phoneState) == -1) {
        Notification({
            title: '提示',
            type: 'warning',
            duration: 1500,
            message: '软电话当前状态不允许外呼！'
        })
        return
    }

    CALL_ID = config.call_id; // 工单id 关联服务记录用
    BUSI_TYPE = config.busi_type; // 关联类型 GD:工单 QZD:求助单
    SOURCE_TYPE_ID = config.sourceTypeId; // 求助来源
    FROM_CODE = config.fromCode; // 来源id
    CUS_CODE = config.cusCode; // 客户id
    CUS_NAME = config.cusName; // 客户姓名
    CUS_CARD = config.cusCard; // 客户证件号
    MOBILE = config.mobile; // 客户手机号码
    

    MakeCall(num, "1");
}

function OnRinging(sAgentID,sUCID,sAni,sDnis,sCTIData)
{
    // Answer(); // 自动接通
}

/**
 * 电话接通后的回调
 * @param {String} sAgentID 坐席工号
 * @param {String} sUCID 通话的唯一ID
 * @param {String} sAni 主叫
 * @param {String} sDnis 被叫
 * @param {String} sDirect 呼叫方向outbound：外呼；inbound：呼入；internal内部呼叫
 * @param {String} sCTIData 随路数据 格式如下： test=1234|test2=1111
 * @param {String} sType 1：普通呼入接通；2：咨询呼入接通；3：会议呼入接通
 */
function OnConnected(sAgentID,sUCID,sAni,sDnis,sDirect,sCTIData,sType)
{   
    store.dispatch('updateSDirect', sDirect);
    store.dispatch('updateSUCID', sUCID);

    if(sDirect == 'inbound') {
        store.dispatch('updateCusNum', sAni);
    }else if(sDirect == 'outbound') {
        store.dispatch('updateCusNum', sDnis);
    }

    let paramObj = {
        // 'Key_IContact_ContactID': getQueryVariable(sCTIData, 'Key_IContact_ContactID'),
        // 'Key_IContact_ANI': getQueryVariable(sCTIData, 'Key_IContact_ANI'),
        // 'Key_IContact_DNIS': getQueryVariable(sCTIData, 'Key_IContact_DNIS'),
        // 'Key_IContact_CallDirection': getQueryVariable(sCTIData, 'Key_IContact_CallDirection'),
        // 'Key_IContact_CallType': getQueryVariable(sCTIData, 'Key_IContact_CallType'),
        // 'BusinessCode': getQueryVariable(sCTIData, 'BusinessCode'),
        'rid': getQueryVariable(sCTIData, 'rid'),
        // 'uid': getQueryVariable(sCTIData, 'uid'),
     };
    //如果是呼入则报工号
    notify("sCTIData=" + JSON.stringify(paramObj));

    router.push({
        path: '/videoScreen/index/' + paramObj.rid,
        query: {
            ...paramObj,
            t: `视频弹屏`
        }
    })
    // let timestamp = new Date().getTime();
    // 转接或咨询 创建联络记录时传入关联记录id
    // let relId;
    // if(tmp_1 == 'ZJ' || tmp_1 == 'ZX') {
    //     relId = from_id
    // }else {
    //     relId = '';
    // }

    // let query = {
    //     sAgentID,
    //     sUCID,
    //     sAni,
    //     sDnis,
    //     sDirect,
    //     sCTIData,
    //     sType,
    //     call_id,
    //     relId,
    //     tmp_1
    // }
    // generateCallLogFun(query).then(data => {
    //     if(sDirect == 'inbound') {
    //         let params = {
    //             ...query,
    //             servId: data.id,
    //             call_id,
    //             user_code,
    //             from_id,
    //             tmp_1
    //         }
    //         router.push({
    //             path: '/autoCallCenter/index/' + timestamp,
    //             query: {
    //                 ...params,
    //                 t: `来电弹屏（${dataHide(params.sAni)}）`
    //             }
    //         })
    //     }
    // })
        
}

/**
 * 电话挂断后的回调
 * @param {String} sAgentID 坐席工号
 * @param {String} sUCID 话路ID
 * @param {String} sReleasePart 挂机方号码
 * @param {String} sReleaseType 挂机类型：1是本座席挂机；2是对方挂机
 */
function OnDisconnected(sAgentID,sUCID,sReleasePart,sReleaseType)
{
    updateEndTimeFun();
    notify("AgentID="+sAgentID+";UCID="+sUCID+";sReleasePart="+sReleasePart+";sReleaseType="+sReleaseType)
}

function generateCallLogFun(query) { // 生成服务记录
    return new Promise((resolve, reject) => {
        let fromWayId;
        let params = {}
        if(query.tmp_1) {
            fromWayId = query.tmp_1;
        }else {
            fromWayId = (query.sDirect == 'inbound' ? 'HR' : 'HC');
        }
        let cusNo;
        let ccNo;
        if(query.sDirect == 'inbound') {
            cusNo = query.sAni;
            ccNo = query.sDnis;
            let params = {
                sourceTypeId: 'SMRX',
                fromTypeId: 'DH',
                fromWayId: fromWayId,
                cusNo: cusNo,
                ccNo: ccNo,
                callId: query.sUCID,
                relId: query.relId
            }
            saveOrUpdateCallLog(params).then(res => {
                if(res.data.code == 1000) {
                    let data = res.data.data;
                    notify('服务记录创建成功！', data)
                    store.dispatch('update_servId', data.id);
                    updateStartTimeFun(data.id);
                    resolve(data);
                    if(query.call_id) { // 如果有工单id 则将工单id与联络记录关联
                        let param = {
                            sheetId: query.call_id,
                            busiType: 'GD',
                            callId: data.id
                        }
                        saveSheetRecContactFun(param);
                    }
                }
            })
        }else if(query.sDirect == 'outbound') {
            cusNo = query.sDnis;
            ccNo = query.sAni;
            let params = {
                sourceTypeId: SOURCE_TYPE_ID,
                fromCode: FROM_CODE,
                fromTypeId: 'DH',
                fromWayId: fromWayId,
                cusNo: cusNo,
                ccNo: ccNo,
                callId: query.sUCID,
                relId: query.relId,
                cusCode: CUS_CODE, // 客户id
                cusName: CUS_NAME, // 客户姓名
                cusCard: CUS_CARD, // 客户证件号
                mobile: MOBILE, // 客户手机号码
            }
            saveOrUpdateCallLog(params).then(res => {
                if(res.data.code == 1000) {
                    let data = res.data.data;
                    notify('服务记录创建成功！', data)
                    store.dispatch('update_servId', data.id);
                    updateStartTimeFun(data.id);
                    resolve(data);
                    notify('CALL_ID', CALL_ID);
                    if(CALL_ID) { // 如果有工单id 则将工单id与联络记录关联
                        let param = {
                            sheetId: CALL_ID,
                            busiType: BUSI_TYPE,
                            callId: data.id
                        }
                        saveSheetRecContactFun(param);
                    }
                }
            })
        }
    })
}

function updateStartTimeFun(id) { // 更新接通时间
    let params = {
        id: id
    }
    updateStartTime(params).then(res => {
        if(res.data.code == 1000) {
            notify('接通时间更新成功！');
        }
    })
}

function updateEndTimeFun() { // 更新挂断时间
    let servId = store.state.phone.servId;
    if(!servId) return;
    let params = {
        id: servId
    }
    updateEndTime(params).then(res => {
        if(res.data.code == 1000) {
            notify('挂断时间更新成功！');
        }
    })
}

function saveSheetRecContactFun(param) { // 工单与服务记录关联
    let params = {
        busiType: param.busiType,
        sheetId: param.sheetId,
        callId: param.callId
    }
    saveSheetRecContact(params).then(res => {
        if(res.data.code == 1000) {
            notify('工单与服务记录关联成功！');
        }
        CALL_ID = null;
        BUSI_TYPE = null;
    })
}

function OnError(sAgentID,sErrorCode,sErrorDisp)
{
    Notification({
        title: '提示',
        type: 'warning',
        duration: 1500,
        message: sErrorDisp
    });
}

function notify(...msg) {
    // if(process.env.NODE_ENV === 'production') return;
    console.log(...msg)
}

function getQueryVariable(str, variable)
{
    var query = str;
    var vars = query.split(";");
    for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            if(pair[0] == variable){return pair[1];}
    }
    return(false);
}

export { statedisc, StateInit, OnSoftPhoneEvent, OnWebSocketDisConnect, makeCallFun }